#!/bin/bash

# 定义微服务名称和路径
APP_NAMES=("repair-admin" "repair-auth" "repair-gateway" "repair-app-start")
APP_HOME_BASE="/home/admin/application"
APP_VERSION="0.0.1-SNAPSHOT"

PROG_NAME=$0
ACTION=$1

usage() {
    echo "Usage: $PROG_NAME {start|stop|restart}"
    exit 2
}

start_application() {
    local app_name=$1

    if [[ $app_name == "repair-app-start" ]]; then
        local jar_name="${APP_HOME_BASE}/repair-service/repair-app-start/target/${app_name}-${APP_VERSION}.jar"
    else
        local jar_name="${APP_HOME_BASE}/${app_name}/target/${app_name}-${APP_VERSION}.jar"
    fi

    echo "Starting ${app_name} java process..."
    nohup java -jar ${jar_name} > /dev/null 2>&1 &
    echo "Started ${app_name} java process."
}

stop_application() {
    local app_name=$1
    local checkjavapid=$(ps -ef | grep java | grep ${app_name} | grep -v grep | awk '{print $2}')

    if [[ ! $checkjavapid ]]; then
        echo "No java process for ${app_name}."
        return
    fi

    echo "Stopping ${app_name} java process..."
    kill -9 $checkjavapid
    echo "${app_name} java process has been stopped."
}

start() {
    for app_name in "${APP_NAMES[@]}"; do
        start_application "${app_name}"
    done
}

stop() {
    for app_name in "${APP_NAMES[@]}"; do
        stop_application "${app_name}"
    done
}

case "$ACTION" in
    start)
        start
        ;;
    stop)
        stop
        ;;
    restart)
        stop
        start
        ;;
    *)
        usage
        ;;
esac
